package charlie.shop.admin;

import com.charlie.beans.Roles;
import com.charlie.beans.Users;
import com.charlie.beans.UsersRole;
import com.charlie.sessions.RolesFacadeLocal;
import com.charlie.sessions.UsersFacadeLocal;
import com.charlie.sessions.UsersRoleFacadeLocal;
import java.io.IOException;
import java.util.Date;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Create new user servlet
 * 
 * @author Оленка
 */
@WebServlet(name = "CreateUser", urlPatterns = {"/admin/createUser"})
public class CreateUser extends HttpServlet {

    @EJB
    private UsersFacadeLocal usersFacade;
    @EJB
    private RolesFacadeLocal rolesFacade;
    @EJB
    private UsersRoleFacadeLocal usersRoleFacade;

    /**
     * Process roles information
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("rolesList", rolesFacade.findAll());
        response.setContentType("text/html;charset=UTF-8");
        getServletContext().getRequestDispatcher("/admin/createUser.jsp").forward(request, response);
    }

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Create new user
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        boolean errors = false;

        String email = request.getParameter("email");
        String first_name = request.getParameter("first_name");
        String second_name = request.getParameter("second_name");
        String password = request.getParameter("pass");
        String password2 = request.getParameter("pass2");
        String location = request.getParameter("location");

        if (email == null || email.length() == 0) {
            errors = true;
        } else {
            if (!usersFacade.emailIsValid(email)) {
                errors = true;
            } else if (usersFacade.findByEmail(email) != null) {
                errors = true;
                request.setAttribute("email_exist", email);
            }
        }

        if (password == null || password.length() == 0 || !password.equals(password2)) {
            errors = true;
        }

        if (!usersFacade.nameIsValid(first_name)) {
            errors = true;
        }

        if (!usersFacade.nameIsValid(second_name)) {
            errors = true;
        }
       
        if (location == null || location.length() == 0) {
            errors = true;
        }

        if (errors) {
            request.setAttribute("validate", true);
            processRequest(request, response);
            return;
        }

        Users user = new Users();
        user.setEmail(email);
        user.setPassword(password);
        user.setFirstName(first_name);
        user.setSecondName(second_name);
        user.setLocation(location);
        user.setCreationDate(new Date());
        user.setUserStatus(1);

        usersFacade.create(user);

        String select[] = request.getParameterValues("id");
        if (select != null) {
            if (select.length != 0) {
                for (String roleName : select) {
                    UsersRole ur = new UsersRole();
                    Roles r = rolesFacade.findByRolesName(roleName);
                    ur.setRolesId(r);
                    ur.setUsersId(user);
                    usersRoleFacade.create(ur);
                }
            }
        }

        response.setContentType("text/html;charset=UTF-8");
        getServletContext().getRequestDispatcher("/admin/completeCreation.jsp").forward(request, response);
    }
}
